/*
	This file is part of Limpet.

    Limpet is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Limpet is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Limpet.  If not, see http://www.gnu.org/licenses/.
	
	Copyright 2010 Dan Popick
*/
var key;

function decodeMultipartData(base64String) {
    var decodedData = Base64.decode(base64String);
    var iv = decodedData.slice(1, decodedData[0] + 1);
    decodedData = decodedData.slice(decodedData[0] + 1);

    GibberishAES.size(256);
    return GibberishAES.rawDecrypt(decodedData, key, iv, false);
}

function findLimpetDiv() {
	var result = document.getElementById("_limpet_div");
    if (!result)
        return;
    
    var text = decodeMultipartData(result.textContent.replace(/\s*/g, ''));
    
	result = result ? JSON.parse(text) : null;
	if (result) {
		chrome.extension.sendRequest(
			{
				command: "pageLoaded",
				url: document.location,
				data: result
			});
	} else {
		chrome.extension.sendRequest(null);
	}
}

function cookieExists(name) {
	return 
		document.cookie.length > 0 && 
		(document.cookie.indexOf(name + "=") >= 0 ||
		 document.cookie.indexOf("=limpet_enabled"));
}

function setCookie(name) {
	if (!cookieExists(name))
		document.cookie = name + "=limpet_enabled; path=/";
}

function checkAndSetCookie() {
	chrome.extension.sendRequest(
		{
			command: "getSettingsByUrl",
			url: document.location,
		},
		function(site) { 
			console.log("Limpet match found: " + site.name);
            key = Base64.decode(site.key);
			setCookie(site.cookieName);
            findLimpetDiv();
		});
}

checkAndSetCookie();

